package net.wanho.hospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.wanho.hospital.po.Drug;
import net.wanho.hospital.mapper.DrugMapper;
import net.wanho.hospital.service.DrugService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 汤小洋
 * @since 2023-12-27
 */
@Service
public class DrugServiceImpl extends ServiceImpl<DrugMapper, Drug> implements DrugService {

   /**
    *   按查询分页查询
    */
    @Override
    public IPage<Drug> findPage(int pageNum, int pageSize,Drug drug) {
        QueryWrapper<Drug> wrapper = null;
        IPage<Drug> page = new Page<>(pageNum, pageSize);
        page = this.page(page, wrapper);
        return page;
    }

    @Override
    public Map<String, Object> findAllDrugs(Integer pageNum, Integer pageSize, String drName) {
        Page<Drug> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<Drug> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!ObjectUtils.isEmpty(drName), Drug::getDrName, drName);

        this.page(page, wrapper);

        Map<String,Object> map  =new HashMap<>();
        map.put("drugs", page.getRecords());
        map.put("total", page.getTotal());

        return map;
    }

    @Override
    public void reduceDrugNumber(Integer drId, Integer usedNumber) {
        Drug drug = this.getById(drId);
        // 判断库存是否足够
        if (drug.getDrNumber() < usedNumber) {
            throw new RuntimeException("库存不足");
        }
        drug.setDrNumber(drug.getDrNumber() - usedNumber);
        this.updateById(drug);
    }

}
